package wiki.zimo.utils;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMessage.RecipientType;
import java.util.Properties;

/**
 * 邮件工具类
 *
 * @author 子墨
 * @date 2018年5月24日 下午2:42:23
 */
public class MailUtils {

    /**
     * 发送QQ邮件
     *
     * @param email
     * @param emailMsg
     * @throws AddressException
     * @throws MessagingException
     */
    public static void sendQQMail(String emailAddress, String emailTitle, String emailMsg)
            throws AddressException, MessagingException {

        final Properties props = new Properties();
        // 设置smtp发送邮件必须经过身份验证
        props.put("mail.smtp.auth", true);
        // 设置smtp服务器为qq邮箱
        props.put("mail.smtp.host", "smtp.qq.com");
        // 设置端口号
        props.put("mail.smtp.port", "587");

        // 设置发送邮件的账号
        props.put("mail.user", "461009747@qq.com");
        // 设置口令
        props.put("mail.password", "qiiwgcjyuhjsbhbc");
        // 创建验证器
        Authenticator auth = new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                String userName = props.getProperty("mail.user");
                String password = props.getProperty("mail.password");
                return new PasswordAuthentication(userName, password);
            }
        };

        // 使用环境属性信息创建邮件会话
        Session session = Session.getInstance(props, auth);
        // 创建Message->邮件内容
        Message message = new MimeMessage(session);
        // 设置发送者
        message.setFrom(new InternetAddress(props.getProperty("mail.user")));
        // 设置发送方式与接收者
        message.setRecipient(RecipientType.TO, new InternetAddress(emailAddress));
        // 设置邮件标题
        message.setSubject(emailTitle);
        // 设置邮件内容
        message.setContent(emailMsg, "text/html;charset=utf-8");
        // 创建 Transport用于将邮件发送
        Transport.send(message);
    }
}
